﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WJP.Dependency;
using WJP.Domain;
using WJP.Reflection;
using WJP.WCF;

namespace WJP
{
    /// <summary>
    /// 控制器
    /// </summary>
    public abstract class DomainController : IPortalFetchable
    {
        public IIocManager IocManager { get; set; }

        private Dictionary<Type, Type> _proxyType = new Dictionary<Type, Type>();

        [IgnoreProxy]
        internal void InnerDependon(DomainController controller)
        {
            OnAlwaysDependon(controller);
        }

        /// <summary>
        /// 使用了 Dependency 方法创建了监听关系，则需要重写次方法来建立确切的事件监听程序
        /// </summary>
        /// <param name="controller"></param>
        [IgnoreProxy]
        protected virtual void OnAlwaysDependon(DomainController controller)
        {
            throw new NotImplementedException("使用了 Dependency 方法创建了监听关系，则需要重写次方法来建立确切的事件监听程序。");
        }

        /// <summary>
        /// 控制器依赖
        /// </summary>
        /// <typeparam name="TController"></typeparam>
        /// <returns></returns>
        public static ControllerDependency Depend<TController>()
        {
            return new ControllerDependency()
            {
                ControllerType = typeof(TController),
            };
        }

        /// <summary>
        /// 服务端使用反射动态调用一个方法
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        object IPortalFetchable.Fetch(object parameter)
        {
            if (!(parameter is CallMethodInfo callMethodInfo))
                throw new AppException("DomainController");
            MethodCaller.CallMethodIfImplemented(IocManager.Resolve(GetProxyClassRealType()), callMethodInfo.MethodName, callMethodInfo.Parameters, out object result);
            return result;
        }

        private Type GetProxyClassRealType()
        {
            if (_proxyType.ContainsKey(GetType()))
                return _proxyType[GetType()];

            var instance = Activator.CreateInstance(GetType());
            if (ProxyUtil.IsProxy(instance))
            {
                var realType = ProxyUtil.GetUnproxiedType(instance);
                _proxyType.Add(GetType(), realType);
                return realType;
            }
            else
                return GetType();
        }

        /// <summary>
        /// 持久化实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        protected virtual void Save<T>(T entity) where T : DataEntity, new()
        {
            if (entity.PersistenceStatus == PersistenceStatus.Unchanged)
                return;

            OnSaving(entity);
            if (entity.PersistenceStatus == PersistenceStatus.New)
            {
                entity.CreateBy = PlatformEnvironment.Identity;
                entity.CreateDate = DateTime.Now;
                entity.UpdateBy = PlatformEnvironment.Identity;
                entity.UpdateDate = DateTime.Now;
            }
            else if (entity.PersistenceStatus == PersistenceStatus.Deleted)
            {
                
            }
            else if (entity.PersistenceStatus == PersistenceStatus.Modified)
            {
                entity.UpdateBy = PlatformEnvironment.Identity;
                entity.UpdateDate = DateTime.Now;
            }
        }

        /// <summary>
        /// 保存前方法
        /// </summary>
        /// <param name="entity"></param>
        protected virtual void OnSaving(IEntity entity)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        protected virtual T GetById<T>(int id) where T : DataEntity, new()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 控制器依赖
        /// </summary>
        public class ControllerDependency
        {
            internal Type ControllerType;

            internal ControllerDependency() { }

            /// <summary>
            /// 始终需要监听指定的控制器类型
            /// </summary>
            /// <typeparam name="TListendController"></typeparam>
            public void On<TListendController>() where TListendController : DomainController
            {
                DomainControllerFactory.CreateDependency(this.ControllerType, typeof(TListendController));
            }

            /// <summary>
            /// 始终需要监听指定的控制器类型
            /// </summary>
            /// <param name="controllerTypes"></param>
            public void On(params Type[] controllerTypes)
            {
                foreach (Type controllerType in controllerTypes)
                    DomainControllerFactory.CreateDependency(this.ControllerType, controllerType);
            }
        }
    }
}
